#!/bin/bash
#
# This script ensures that lua interpreter is installed.
#
# Environment variables:
#   LUA_VERSION    : Required version of the lua interpreter (e.g. lua-5.2, luajit-2). If this
#                    version is not available on PATH and USE_SYSTEM_LUA != 'yes', then it will be
#                    installed, otherwise it fails.
#                    If not set, then the script checks if lua-5.2, lua-5.3, or luajit-2 is
#                    available. If not and USE_SYSTEM_LUA != 'yes', then lua-5.1 will be installed,
#                    otherwise it fails.
#
#   USE_SYSTEM_LUA : Set to 'yes' if you want to use system provided lua. Default is to install
#                    lua locally in .env directory.
set -e

DEFAULT_VERSION='lua-5.2'
PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
VENV_DIR="$PROJECT_DIR/.env"
HEREROCKS_URI='https://raw.githubusercontent.com/mpeterv/hererocks/master/hererocks.py'


#======================  Functions  ======================#

die() {
    echo -e "ERROR: $1" >&2
    exit ${2:-2}
}

exists() {
    command -v "$1" &>/dev/null
}

find-lua-exec() {
    local cmd; for cmd in lua luajit; do
        if exists "$cmd"; then
            command -v "$cmd"
            return 0
        fi
    done
    return 1
}

check-lua-version() {
    local luabin="$1"
    local ver="$($luabin -v 2>&1 | cut -d' ' -f1-2 | tr '[A-Z] ' '[a-z]-' || '')"

    if [ -n "$LUA_VERSION" ]; then
        [[ "$ver" == "$LUA_VERSION"* ]]
    else
        [[ "$ver" =~ ^lua-5.[23]|^luajit-2 ]]
    fi
}

install-lua() {
    local version=$1

    mkdir -p "$VENV_DIR"
    curl -o "$VENV_DIR/hererocks.py" "$HEREROCKS_URI"
    python "$VENV_DIR/hererocks.py" "$VENV_DIR" --luarocks=^ --${version/-/=}
}


#========================  Main  =========================#

cd "$PROJECT_DIR"

if [[ "$USE_SYSTEM_LUA" == y* ]]; then

    if ! check-lua-version "$(find-lua-exec)"; then
        die "${LUA_VERSION:-lua 5.1-5.2 or luajit 2} is not installed and USE_SYSTEM_LUA=$USE_SYSTEM_LUA"

    elif ! exists luarocks; then
        die "luarocks is not installed and USE_SYSTEM_LUA=$USE_SYSTEM_LUA"
    fi

else
    export PATH="$VENV_DIR/bin:$PATH"

    if ! check-lua-version "$VENV_DIR/bin/lua" || [ ! -x "$VENV_DIR/bin/luarocks" ]; then
        version="${LUA_VERSION:-$DEFAULT_VERSION}"

        echo "==> Installing $version and luarocks into $VENV_DIR..." >&2
        install-lua $version
    fi
fi
